package com.helint.transfer.controller;

import com.sun.javafx.binding.StringConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * 中转服务controller
 *
 * @author junjun
 */
@Controller
@Slf4j
public class TransferController {

    @Autowired
    private Environment environment;

    private static final String POST = "post";
    private static final String GET = "get";
    private static final String FROM_CONTENT_TYPE = "application/x-www-form-urlencoded";
    private static final String JSON_CONTENT_TYPE = "application/json;charset=utf-8";
    /**
     * 设备ID
     */
    private static final String EQUIPMENT_ID = "EQUIPMENT_ID";
    /**
     * 系统CODE
     */
    private static final String SYS_CODE = "SYS_CODE";

    /**
     * 解析转发
     *
     * @param request
     * @param response
     */
    @RequestMapping("/*/**")
    public void transfer(HttpServletRequest request, HttpServletResponse response) {
        // 获取系统code
        String sysCode = request.getHeader(SYS_CODE);
        String requestUrlPath = request.getRequestURI();
        log.info("#### requestUrlPath: {}", requestUrlPath);
        Map<String, Object> map = new HashMap<>();
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
            map.put(key, value);
        }
        String url = environment.getProperty(sysCode) + requestUrlPath;
        String param = request.getQueryString();
        if (param != null) {
            url += "?" + param;
        }
        BufferedReader br;
        String str = "";
        String postParam = "";
        try {
            br = request.getReader();
            while ((str = br.readLine()) != null) {
                postParam += str;
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
        }
        String contentType = FROM_CONTENT_TYPE;
        contentType = request.getContentType();
        String method = request.getMethod();
        String result = "";
        /*if (POST.equalsIgnoreCase(method) && contentType.indexOf("xml") != -1) {
            BigDataScoreClient client = new BigDataScoreClient();
            try {
                client.setUrl(url);
                CloseableHttpClient httpClient = BigDataScoreClient.getHttpClient();
                result = client.execute(httpClient, postParam);
                // 设置响应头
                response.setHeader(EQUIPMENT_ID, request.getHeader(EQUIPMENT_ID));//设置header
                response.setContentType("text/xml;charset=utf-8");
            } catch (Exception e) {
                log.error(e.getMessage());
                e.printStackTrace();
            }
        }  */
        if (POST.equalsIgnoreCase(method)) {
            result = sendPost(url, postParam, map);
            // 设置header
            response.setHeader(EQUIPMENT_ID, request.getHeader(EQUIPMENT_ID));
            response.setContentType( JSON_CONTENT_TYPE );
        } else if (GET.equalsIgnoreCase(method)) {
            result = sendGet(url, map);
            // 设置header
            response.setHeader(EQUIPMENT_ID, request.getHeader(EQUIPMENT_ID));
            response.setContentType( JSON_CONTENT_TYPE );
        }
        // 编码
        response.setCharacterEncoding("utf-8");
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        PrintWriter out = null;
        try {
            out = response.getWriter();
            log.info("#### result： " + result);
            out.write(result);
            out.flush();
        } catch (IOException e) {
            log.error(e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * POST请求
     *
     * @param url
     * @param param
     * @param headerMap
     * @return
     */
    private String sendPost(String url, String param, Map<String, Object> headerMap) {
        PrintWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        try {
            URL realUrl = new URL(url);
            // 创建连接
            URLConnection conn = realUrl.openConnection();
            // 设置请求
//            conn.setRequestProperty("accept", "*/*");
//            conn.setRequestProperty("connection", "Keep-Alive");
//            conn.setRequestProperty("user-agent",
//                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 设置header
            for (Map.Entry item : headerMap.entrySet()) {
                conn.setRequestProperty(item.getKey().toString(), item.getValue().toString());
            }
            // POST
            conn.setDoOutput(true);
            conn.setDoInput(true);
            out = new PrintWriter(conn.getOutputStream());
            out.print(param);
            out.flush();
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8.name()));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
        } catch (Exception e) {
            log.error("#### post error: ", e);
        }
        // 关闭资源
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                log.error("#### post finally error: ", ex);
            }
        }
        return result.toString();
    }

    /**
     * GET请求
     *
     * @param url
     * @param headerMap
     * @return
     */
    private String sendGet(String url, Map<String, Object> headerMap) {
        StringBuilder result = new StringBuilder();
        BufferedReader in = null;
        try {
            URL realUrl = new URL(url);
            URLConnection connection = realUrl.openConnection();
//            connection.setRequestProperty("accept", "*/*");
//            connection.setRequestProperty("connection", "Keep-Alive");
//            connection.setRequestProperty("user-agent",
//                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 设置header
            for (Map.Entry item : headerMap.entrySet()) {
                connection.setRequestProperty(item.getKey().toString(), item.getValue().toString());
            }
            connection.connect();
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream(), StandardCharsets.UTF_8.name()));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
        } catch (Exception e) {
            log.error("#### get error: ", e);
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                log.error("#### get finally error: ", e2);
            }
        }
        return result.toString();
    }
}
